<?php
//include dirname(dirname(dirname(dirname(dirname(__FILE__))))).'/np/np_string.php';
//echo dirname(dirname(dirname(dirname(dirname(__FILE__))))).'/np/np_string.php';die;
class child_c2_task_model
{

	//添加主媒资
	static public function add_series($vod_info,$sp_id)
	{
		$action = 'REGIST';
		$vod_info['nns_action'] = $action;
		//设置失效时间
		$t = 3600*24*30*12*7;
		$vod_info['nns_end_time'] = strtotime($vod_info['nns_create_time']) + $t;
		//       echo $t=date('Y-m-d H:i:s',$vod_info['nns_end_time']);
		//       echo '<pre>';
		//       print_r($vod_info);die;
		$xml_str = self::__series_xml($vod_info);

		$c2_id = np_guid_rand(null,20);

		$file_name = 'series_'.$vod_info['nns_id'].'_'.$action.'.xml';
		$c2_info = array(
					'nns_id' => $c2_id,
					'nns_task_type'=>'Series',
					'nns_task_id'=> $vod_info['nns_task_id'],
					'nns_task_name'=> $vod_info['nns_task_name'],
					'nns_action'=>	$action,
					'nns_url' => $file_name,
					'nns_content' => $xml_str,
					'nns_desc' => 'Series,'.$action,
		);
		$result = self::execute_c2_child($c2_info, $sp_id);
		return $result;
	}
	//修改主媒资
	static public function update_series($vod_info,$sp_id)
	{
		$action = 'UPDATE';
		$vod_info['nns_action'] = $action;
		//设置失效时间
		$t = 3600*24*30*12*7;
		$vod_info['nns_end_time'] = strtotime($vod_info['nns_create_time']) + $t;
		//       echo $t=date('Y-m-d H:i:s',$vod_info['nns_end_time']);
		//       echo '<pre>';
		//       print_r($vod_info);die;
		$xml_str = self::__series_xml($vod_info);

		$c2_id = np_guid_rand(null,20);

		$file_name = 'series_'.$vod_info['nns_id'].'_'.$action.'.xml';

		$c2_info = array(
					'nns_id' => $c2_id,
					'nns_task_type'=>'Series',
					'nns_task_id'=> $vod_info['nns_task_id'],
					'nns_task_name'=> $vod_info['nns_task_name'],
					'nns_action'=>	$action,
					'nns_url' => $file_name,
					'nns_content' => $xml_str,
					'nns_desc' => 'Series,'.$action,
		);
		$result = self::execute_c2_child($c2_info, $sp_id);
		return $result;
	}
	//删除主媒资
	static public function delete_series($vod_info,$sp_id)
	{
		$action = 'DELETE';
		$vod_info['nns_action'] = $action;
		//设置失效时间
		$t = 3600*24*30*12*7;
		$vod_info['nns_end_time'] = strtotime($vod_info['nns_create_time']) + $t;
		//       echo $t=date('Y-m-d H:i:s',$vod_info['nns_end_time']);
		//       echo '<pre>';
		//       print_r($vod_info);die;
		$xml_str = self::__delete_series_xml($vod_info);

		$c2_id = np_guid_rand(null,20);

		$file_name = 'series_'.$vod_info['nns_id'].'_'.$action.'.xml';

		$c2_info = array(
					'nns_id' => $c2_id,
					'nns_task_type'=>'Series',
					'nns_task_id'=> $vod_info['nns_task_id'],
					'nns_task_name'=> $vod_info['nns_task_name'],
					'nns_action'=>	$action,
					'nns_url' => $file_name,
					'nns_content' => $xml_str,
					'nns_desc' => 'Series,'.$action,
		);
		$result = self::execute_c2_child($c2_info, $sp_id);
		return $result;
	}
	//添加分集
	static public function add_vod($vod_info,$sp_id)
	{
		$action = 'REGIST';

		$t = 3600*24*30*12*7;
		$vod_info['nns_end_time'] = strtotime($vod_info['nns_create_time']) + $t;
		$vod_info['nns_action'] = $action;
		$xml_str = self::__vod_xml($vod_info);
		$c2_id = np_guid_rand(null,20);

		$file_name = 'vod_'.$vod_info['nns_id'].'_'.$action.'.xml';

		$c2_info = array(
					'nns_id' => $c2_id,
					'nns_task_type'=>'Program',
					'nns_task_id'=> $vod_info['nns_task_id'],
					'nns_task_name'=> $vod_info['nns_task_name'],
					'nns_action'=>	$action,
					'nns_url' => $file_name,
					'nns_content' => $xml_str,
					'nns_desc' => 'Program,'.$action,
		);
		$result = self::execute_c2_child($c2_info, $sp_id);
		return $result;
	}
	//修改分集
	static public function update_vod($vod_info,$sp_id)
	{
		$action = 'UPDATE';
		$t = 3600*24*30*12*7;
		$vod_info['nns_end_time'] = strtotime($vod_info['nns_create_time']) + $t;
		$vod_info['nns_action'] = $action;
		$xml_str = self::__vod_xml($vod_info);
		$c2_id = np_guid_rand(null,20);

		$file_name = 'vod_'.$vod_info['nns_id'].'_'.$action.'.xml';


		$c2_info = array(
					'nns_id' => $c2_id,
					'nns_task_type'=>'Program',
					'nns_task_id'=> $vod_info['nns_task_id'],
					'nns_task_name'=> $vod_info['nns_task_name'],
					'nns_action'=>	$action,
					'nns_url' => $file_name,
					'nns_content' => $xml_str,
					'nns_desc' => 'Program,'.$action,
		);
		$result = self::execute_c2_child($c2_info, $sp_id);
		return $result;
	}
	//删除分集
	static public function delete_vod($vod_info,$sp_id)
	{
		$action = 'DELETE';
		$t = 3600*24*30*12*7;
		$vod_info['nns_end_time'] = strtotime($vod_info['nns_create_time']) + $t;
		$vod_info['nns_action'] = $action;
		$xml_str = self::__delete_vod_xml($vod_info);
		$c2_id = np_guid_rand(null,20);

		$file_name = 'vod_'.$vod_info['nns_id'].'_'.$action.'.xml';

		$c2_info = array(
					'nns_id' => $c2_id,
					'nns_task_type'=>'Program',
					'nns_task_id'=> $vod_info['nns_task_id'],
					'nns_task_name'=> $vod_info['nns_task_name'],
					'nns_action'=>	$action,
					'nns_url' => $file_name,
					'nns_content' => $xml_str,
					'nns_desc' => 'Program,'.$action,
		);
		$result = self::execute_c2_child($c2_info, $sp_id);
		return $result;
	}
	//添加片源
	static public function add_movie($movie_info,$sp_id)
	{
		$action = 'REGIST';
		include dirname(dirname(__FILE__)).'/define.php';
		$url = MOVIE_FTP.$movie_info['nns_file_path'];

		$movie_info['nns_action'] = $action;
		$movie_info['nns_file_url'] = $url;
		$xml_str = self::__movie_xml($movie_info);
		$c2_id = np_guid_rand(null,20);

		$file_name = 'vod_media_'.$movie_info['nns_video_index_id'].'_'.$movie_info['nns_media_id'].'_'.$action.'.xml';

		$bool = self::child_check_ftp_file($url);

		if($bool===false){
			$re = nl_execute_by_db("update nns_mgtvbk_c2_task set nns_status=-1 where nns_id='{$movie_info['nns_task_id']}'", $db);
			include_once dirname(dirname(dirname(__FILE__))).'/models/queue_task_model.php';
			$queue_task_model = new queue_task_model();
			DEBUG && i_write_log_core('path_fail----'.$url,$sp_id.'/path_fail');
			$queue_task_model->q_re_clip($movie_info['nns_task_id']);
			$queue_task_model=null;
			return false;
		}
		$c2_info = array(
					'nns_id' => $c2_id,
					'nns_task_type'=>'Movie',
					'nns_task_id'=> $movie_info['nns_task_id'],
					'nns_task_name'=> $movie_info['nns_task_name'],
					'nns_action'=>	$action,
					'nns_url' => $file_name,
					'nns_content' => $xml_str,
					'nns_desc' => 'Movie,'.$action,
		);
		$result = self::execute_c2_child($c2_info, $sp_id);
		return $result;
	}
	//修改片源
	//	static public function update_movie($movie_info,$sp_id)
	//	{
	//		$action = 'UPDATE';
	//		$vod_info['nns_action'] = $action;
	//		$xml_str = self::__movie_xml($vod_info);
	//		$c2_id = np_guid_rand(null,20);
	//
	//		$file_name = 'vod_media_'.$movie_info['nns_video_index_id'].'_'.$movie_info['nns_media_id'].'_'.$action.'.xml';
	//
	//		$c2_info = array(
	//					'nns_id' => $c2_id,
	//					'nns_task_type'=>'Movie',
	//					'nns_task_id'=> $movie_info['nns_task_id'],
	//					'nns_task_name'=> $movie_info['nns_task_name'],
	//					'nns_action'=>	$action,
	//					'nns_url' => $file_name,
	//					'nns_content' => $xml_str,
	//					'nns_desc' => 'Movie,'.$action,
	//		);
	//		$result = self::execute_c2_child($c2_info, $sp_id);
	//		return $result;
	//	}
	//删除片源
	static public function delete_movie($movie_info,$sp_id)
	{
		$action = 'DELETE';
		$movie_info['nns_action'] = $action;
		$xml_str = self::__delete_movie_xml($movie_info);
		$c2_id = np_guid_rand(null,20);

		$file_name = 'vod_media_'.$movie_info['nns_video_index_id'].'_'.$movie_info['nns_media_id'].'_'.$action.'.xml';

		$c2_info = array(
					'nns_id' => $c2_id,
					'nns_task_type'=>'Movie',
					'nns_task_id'=> $movie_info['nns_task_id'],
					'nns_task_name'=> $movie_info['nns_task_name'],
					'nns_action'=>	$action,
					'nns_url' => $file_name,
					'nns_content' => $xml_str,
					'nns_desc' => 'Movie,'.$action,
		);
		$result = self::execute_c2_child($c2_info, $sp_id);
		return $result;
	}

	//上传xml文件
	static public function execute_c2_child($c2_info,$sp_id){
		$c2_id = $c2_info['nns_id'];
		$sub_path = date('Y-m-d');
		$file = $c2_info['nns_url'];
		$c2_info['nns_url'] = $sub_path.'/'.$file;
		$xml_str = $c2_info['nns_content'];
		$file_path = dirname(dirname(dirname(dirname(__FILE__)))).'/data/mgtv/'.$sp_id.'/inject_xml/'.$sub_path.'/';

		if(!is_dir($file_path)) mkdir($file_path,0777,true);
		$file_path .= $file;
		//die($file_path);
		file_put_contents($file_path,$xml_str);
		if(!self::exists_c2_commond_child($c2_info,$sp_id)){

			//echo $xml_str;die;
			include dirname(dirname(__FILE__)).'/define.php';
			//include dirname(dirname(dirname(__FILE__))).'/utils.func.php';

			$CmdFileURL = C2_FTP.$c2_info['nns_url'];
			//写入日志
			i_write_log_core($CmdFileURL,'c2_soap');
			//echo dirname(dirname(dirname(__FILE__))).'/utils.func.php'.$CmdFileURL;die;
			//echo '22';
			$soap = self::__soap($c2_id,$CmdFileURL);
			//echo $soap;die;
			if($soap == 0){
				$c2_info['nns_result'] = '[0]';
			}else{
				$c2_info['nns_result'] = "[-1]";
			}
			self::save_c2_log_child($c2_info,$sp_id);
			return true;
		}

		return false;
	}
	//写入注入日志
	static public function save_c2_log_child($c2_log,$sp_id){
		$db = nn_get_db(NL_DB_WRITE);
		//$db->open();
		$c2_log['nns_type'] = 'std';
		$c2_log['nns_org_id'] = $sp_id;
		$dt = date('Y-m-d H:i:s');
		$c2_log['nns_create_time'] = $dt;
		$c2_log['nns_send_time'] = $dt;
		return nl_db_insert($db,'nns_mgtvbk_c2_log',$c2_log);
	}
	static public function exists_c2_commond_child($c2_info,$sp_id){
		$db_r = nn_get_db(NL_DB_READ);
		$nns_org_id = $sp_id;
		$nns_task_type = $c2_info['nns_task_type'];
		$nns_task_id = $c2_info['nns_task_id'];
		$nns_action = $c2_info['nns_action'];

		if(empty($nns_task_id)) return false;
		$start_time = date('Y-m-d').' 00:00:00';
		$end_time = date('Y-m-d').' 23:59:59';
		$count = "select count(1) as num from nns_mgtvbk_c2_log where nns_org_id='{$sp_id}' and nns_task_id='{$nns_task_id}' and nns_task_type='{$nns_task_type}' and nns_action='{$nns_action}' and nns_create_time>='{$start_time}' and nns_create_time<='{$end_time}' and nns_notify_result is null";
		$c = nl_db_get_col($count, $db_r);
		if($c>=2){
			return true;
		}
	}
	//soap接口调用
	private static function __soap($id,$params){
		include_once dirname(dirname(dirname(dirname(__FILE__)))).'/mgtv/sp_nmgu/soap/nmgu_client.php';

		//CSPID MGTV
		//SOPID NMQN
		//CorrelateID mg000001   (后面000001是唯一标识)
		//ContentMngXMLURL
		//ftp://nmlt:nmlt@1.25.203.230:21/ftp/cms/aa.xml

		$CmdFileURL = $params;
		$CorrelateID = $id;
		$ret = nmgu_client::ContentPublishReq($CorrelateID,$CmdFileURL);
		//print_r($ret);die;
		//这里需要判断下 ==
		return $ret->ResultCode;
	}

	//拼主媒资xml串
	private static function __series_xml($params){
	    
        if(empty($params['nns_all_index'])){
            $db_r = nn_get_db(NL_DB_READ);
            $sql = "select nns_all_index from nns_vod where nns_id='{$params['nns_id']}'";
            $params['nns_all_index'] = nl_db_get_col($sql, $db_r);
        }
        
        
		$xml = '<?xml version="1.0" encoding="UTF-8"?><ADI>
     <Objects>
     <Object ElementType="Series"  ContentID="'.$params['nns_id'].'" Action="'.$params['nns_action'].'">
     <Property Name="Name">'.htmlspecialchars($params['nns_name'], ENT_QUOTES).'</Property>
     <Property Name="CPContentID"/>
     <Property Name="OrderNumber"/>
     <Property Name="CpContentIdIn"/>
     <Property Name="OriginalName"/>
     <Property Name="SortName"/>
     <Property Name="SearchName">'.$params['nns_pinyin'].'</Property>
     <Property Name="Genre"/>
     <Property Name="OriginalCountry"/>
     <Property Name="Language"/>
     <Property Name="ReleaseYear"/>
     <Property Name="OrgAirDate"/>
     <Property Name="LicensingWindowStart">'.strtotime($params['nns_create_time']).'</Property>
     <Property Name="LicensingWindowEnd">'.$params['nns_end_time'].'</Property>
     <Property Name="DisplayAsNew"/>
     <Property Name="DisplayAsLastChance"/>
     <Property Name="Macrovision"/>
     <Property Name="Description">'.htmlspecialchars($params['nns_summary'], ENT_QUOTES).'</Property>
     <Property Name="Pricetaxin">0.00</Property>
     <Property Name="Status">1</Property>
     <Property Name="SourceType">1</Property>
     <Property Name="VolumnCount">'.$params['nns_all_index'].'</Property>    
     <Property Name="SeriesFlag">'.$params['nns_series_flag'].'</Property>
     <Property Name="ContentProvider"/>
     <Property Name="KeyWords"/>
     <Property Name="Tags"/>
     <Property Name="ViewPoint"/>
     <Property Name="StarLevel"/>
     <Property Name="Rating"/>
     <Property Name="Awards"/>
     <Property Name="Length">'.$params['nns_time_len'].'</Property>
     <Property Name="ProgramType"/>
     <Property Name="Reserve1"/>
     <Property Name="Reserve2">'.htmlspecialchars($params['nns_director'], ENT_QUOTES).'</Property>
     </Object>
     </Objects>
     </ADI>';
		return $xml;
	}
	//拼分集xml串
	private static function __vod_xml($params){
	        
        #if(empty($params['nns_vod_id'])){
            $db_r = nn_get_db(NL_DB_READ);
            $sql = "select nns_vod_id,nns_index from nns_vod_index where nns_id='{$params['nns_id']}'";
            $r = nl_db_get_one($sql, $db_r);
            $params['nns_vod_id'] = $r['nns_vod_id'];
            $params['nns_index'] = intval($r['nns_index']+1);
        #}    
	    
		$xml = '<?xml version="1.0" encoding="UTF-8"?><ADI>
     <Objects>
     <Object ElementType="Program"  ContentID="'.$params['nns_id'].'" Action="'.$params['nns_action'].'">
     <Property Name="Name">'.htmlspecialchars($params['nns_name'], ENT_QUOTES).'</Property>
     <Property Name="CPContentID"/>
     <Property Name="OrderNumber"/>
     <Property Name="CpContentIdIn"/>
     <Property Name="OriginalName"/>
     <Property Name="SortName"/>
     <Property Name="SearchName">'.$params['nns_pinyin'].'</Property>
     <Property Name="Genre"/>
     <Property Name="OriginalCountry"/>
     <Property Name="Language"/>
     <Property Name="ReleaseYear"/>
     <Property Name="OrgAirDate"/>
     <Property Name="LicensingWindowStart">'.strtotime($params['nns_create_time']).'</Property>
     <Property Name="LicensingWindowEnd">'.$params['nns_end_time'].'</Property>
     <Property Name="DisplayAsNew"/>
     <Property Name="DisplayAsLastChance"/>
     <Property Name="Macrovision"/>
     <Property Name="Description">'.htmlspecialchars($params['nns_summary'], ENT_QUOTES).'</Property>
     <Property Name="Pricetaxin">0.00</Property>
     <Property Name="Status">1</Property>
     <Property Name="SourceType">1</Property>
     <Property Name="SeriesFlag">'.$params['nns_series_flag'].'</Property>
     <Property Name="ContentProvider"/>
     <Property Name="KeyWords"/>
     <Property Name="Tags"/>
      
     <Property Name="ViewPoint"/>
     <Property Name="StarLevel"/>
     <Property Name="Rating"/>
     <Property Name="Awards"/>
     <Property Name="Length">'.$params['nns_time_len'].'</Property>
     <Property Name="ProgramType"/>
     <Property Name="Reserve1"/>
     <Property Name="Reserve2">'.htmlspecialchars($params['nns_director'], ENT_QUOTES).'</Property>
     </Object>
     </Objects>
     <Mappings>
     <Mapping ParentType="Series" ParentID="'.$params['nns_vod_id'].'" ElementType="Program"
     ElementID="'.$params['nns_id'].'" ObjectID="'.$params['nns_id'].'" Action="'.$params['nns_action'].'">
     <Property Name="Type"/>
     <Property Name="Sequence">'.$params['nns_index'].'</Property>
     <Property Name="ValidStart"/>
     <Property Name="ValidEnd"/>
     </Mapping>
     </Mappings>
     </ADI>';
		return $xml;
	}
	//拼片源xml串
	private static function __movie_xml($params){
	            
	         $db_r = nn_get_db(NL_DB_READ);
            $sql = "select nns_vod_id,nns_index from nns_vod_media where nns_id='{$params['nns_media_id']}'";
            $r = nl_db_get_one($sql, $db_r);
	    
		$xml = '<?xml version="1.0" encoding="UTF-8"?><ADI>
		
     <Objects>
     <Object ElementType="Movie" PhysicalContentID="'.$params['nns_media_id'].'" Action="DELETE" Type="1"></Object>
     <Object ElementType="Movie" PhysicalContentID="'.$params['nns_media_id'].'" Action="'.$params['nns_action'].'" Type="1">
     <Property Name="FileURL">'.$params['nns_file_url'].'</Property>
     <Property Name="SourceDRMType">0</Property>
     <Property Name="AudioType"/>
     <Property Name="ScreenFormat"/>
     <Property Name="ClosedCaptioning"/>
     <Property Name="Duration">'.$r['nns_file_len'].'</Property>
     <Property Name="FileSize">'.$r['nns_file_size'].'</Property>
     <Property Name="BitRateType">0</Property>
     <Property Name="VideoType">1</Property>
     <Property Name="AudioEncodingType">1</Property>
     <Property Name="Resolution">1</Property>
     <Property Name="VideoProfile"/>
     <Property Name="SystemLayer"/>
     <Property Name="Domain"/>
     <Property Name="Hotdegree"/>
     </Object>
     </Objects>
     <Mappings>
     <Mapping ParentType="Program" ParentID="'.$params['nns_video_index_id'].'" ElementType="Movie"
     ElementID="'.$params['nns_media_id'].'" ObjectID="'.$params['nns_media_id'].'" Action="'.$params['nns_action'].'">
     </Mapping>
     </Mappings>
     </ADI>';
		return $xml;
	}
	//拼删除主媒资xml串
	private static function __delete_series_xml($params){
		$xml = '<?xml version="1.0" encoding="UTF-8"?><ADI>
	     <Objects>
	     <Object ElementType="Series"  ContentID="'.$params['nns_id'].'" Action="'.$params['nns_action'].'">
	     </Object>
	     </Objects>
	     </ADI>';
		return $xml;
	}
	//拼删除分集xml串
	private static function __delete_vod_xml($params){
		$xml = '<?xml version="1.0" encoding="UTF-8"?><ADI>
	     <Objects>
	     <Object ElementType="Program"  ContentID="'.$params['nns_id'].'" Action="'.$params['nns_action'].'">
	     </Object>
	     </Objects>
	     </ADI>';
		return $xml;
	}
	//拼删除片源xml串
	private static function __delete_movie_xml($params){
		$xml = '<?xml version="1.0" encoding="UTF-8"?><ADI>
	     <Objects>
	     <Object ElementType="Movie" PhysicalContentID="'.$params['nns_id'].'" Action="'.$params['nns_action'].'" Type="1">
	     </Object>
	     </Objects>
	     </ADI>';
		return $xml;
	}

	static  public function child_check_ftp_file($url){
		//return false;
		$url_arr = parse_url($url);
		$port = isset($url_arr["port"]) ? $url_arr["port"] : 21;
		$time = 10;
		$connect_no=ftp_connect($url_arr['host'],$port,$time);
		if ($connect_no===FALSE) return FALSE;
		@ftp_login(
		$connect_no,
		$url_arr["user"],
		$url_arr["pass"]
		);
		ftp_pasv($connect_no,true);
		$contents = ftp_nlist($connect_no, $url_arr['path']);
		//DEBUG && i_write_log_core('path_fail----'.$url.var_export($contents,true),'sp_nmgu/path_fail_ftp');
		if($contents===false){
			return FALSE;
		}else{
			if(empty($contents)){
				return FALSE;
			}
			return true;
		}
	}
}
